package com.gkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gkd.constant.MessageConstant;
import com.gkd.constant.StatusContant;
import com.gkd.context.BaseContext;
import com.gkd.exception.AlreadyExistsException;
import com.gkd.mapper.LikesMapper;
import com.gkd.pojo.entity.Likes;
import com.gkd.service.LikesService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
* @author ZJF
* @description 针对表【like】的数据库操作Service实现
* @createDate 2024-06-15 18:18:34
*/
@Service
public class LikesServiceImpl extends ServiceImpl<LikesMapper, Likes>
    implements LikesService{

    @Autowired
    private LikesMapper likesMapper;

    /**
     * 添加点赞
     * @param postId
     */
    @Override
    public void add(Integer postId) {
        Likes likes = Likes.builder()
                .postId(postId)
                .userId(BaseContext.getCurrentId())
                .createTime(new Date())
                .build();

        LambdaQueryWrapper<Likes> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Likes::getPostId,likes.getPostId());
        wrapper.eq(Likes::getUserId,likes.getUserId());
        Likes one = likesMapper.selectOne(wrapper);
        if (one!=null){
            throw new AlreadyExistsException(MessageConstant.LIKES_BE_RELATED);
        }
        likesMapper.insert(likes);
    }

    /**
     * 取消点赞
     * @param postId
     */
    @Override
    public void delete(Integer postId) {
        LambdaQueryWrapper<Likes> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Likes::getPostId,postId);
        wrapper.eq(Likes::getUserId,BaseContext.getCurrentId());

        //取消该点赞
        likesMapper.delete(wrapper);
    }

    /**
     * 通过文章id和用户id获取点赞状态
     * @param postId
     * @param userId
     * @return
     */
    @Override
    public String getByPostIdAndUserId(Integer postId, Integer userId) {
        LambdaQueryWrapper<Likes> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Likes::getPostId,postId);
        wrapper.eq(Likes::getUserId,userId);

        Likes like = likesMapper.selectOne(wrapper);
        if (like!=null){
            return StatusContant.FAVORITE_TRUE;
        }else {
            return StatusContant.FAVORITE_FALSE;
        }
    }
}




